package org.xlx.xlx_oa.role_user.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.xlx.xlx_oa.role_user.convertor.RoleUserConvertor;
import org.xlx.xlx_oa.role_user.domain.SysControl;
import org.xlx.xlx_oa.role_user.domain.dto.SysControlDto;
import org.xlx.xlx_oa.role_user.domain.vo.SysControlVo;
import org.xlx.xlx_oa.role_user.mapper.SysControlMapper;

import java.util.List;
import java.util.Objects;

@Service
public class SysControlService {
    private final RoleUserConvertor roleUserConvertor = RoleUserConvertor.INSTANCE;
    @Autowired
    private SysControlMapper sysControlMapper;

    /**
     * 保存
     */
    public Boolean saveEntity(SysControlVo controlVo) {
        SysControl sysControl = roleUserConvertor.convertVoToControl(controlVo);
        Long id = sysControl.getId();
        if (Objects.isNull(id)) {
            sysControlMapper.insert(sysControl);
        } else {
            sysControlMapper.updateById(sysControl);
        }
        return true;
    }

    /**
     * 删除
     */
    public Boolean removeEntity(Long id) {
        return sysControlMapper.deleteById(id) > 0;
    }

    /**
     * 列表
     */
    public List<SysControlDto> getList(SysControlVo controlVo) {
        SysControl sysControl = roleUserConvertor.convertVoToControl(controlVo);
        QueryWrapper<SysControl> wrapper = new QueryWrapper<>();
        if (!Objects.isNull(sysControl.getId())) {
            wrapper.lambda()
                    .eq(SysControl::getId, sysControl.getId())
                    .or()
                    .eq(SysControl::getParentId, sysControl.getId());

        }
        if (!Objects.isNull(sysControl.getControlName())) {
            wrapper.lambda().like(SysControl::getControlName, sysControl.getControlName());
        }
        if (!Objects.isNull(sysControl.getControlUrl())) {
            wrapper.lambda().like(SysControl::getControlUrl, sysControl.getControlUrl());
        }
        Page<SysControl> page = new Page<>(controlVo.getPageNum(), controlVo.getPageSize());
        sysControlMapper.selectPage(page, wrapper);
        List<SysControlDto> dtos = roleUserConvertor.convertToListSysControlDto(page.getRecords());
        return dtos;
    }

    /**
     * 详情
     */
    public SysControlDto getDetail(Long id) {
        SysControl sysControl = sysControlMapper.selectById(id);
        return roleUserConvertor.convertToSysControlDto(sysControl);
    }
}
